﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Transactions;
using System.Web.Mvc;
using System.Web.UI.WebControls;
using ZBJF.Warranty.BLL;
using ZBJF.Warranty.Common.Common;
using ZBJF.Warranty.Common.Enums.Base;
using ZBJF.Warranty.Common.Enums.System;
using ZBJF.Warranty.Model;
using ZBJF.Warranty.Model.ViewModel.Sellers;
using ZBJF.Warranty.WebProvider;

namespace ZBJF.Warranty.AdminSite.Controllers
{
    public class SellersController : BaseController
    {
        //
        // GET: /Sellers/
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public JsonResult Index(SellersModel model)
        {
            var total = 0;
            var list = ServiceFactory.SellersServiceInstance.GetPagingList(model, out total).Include(o => o.SellersOrganization).AsNoTracking().ToList().Select(o => new
            {
                SellersID = o.ID,
                o.ID,
                o.SellerCode,
                o.SellersName,
                SaleSystemTypeName= EnumHelper.Instance.GetDescription(typeof(SaleSystemTypeEnums), o.SaleSystemType),
                SellerTypeName = o.SellersType1 != null ? o.SellersType1.SellerTypeName : string.Empty,
                ParentOrganizationName = ServiceFactory.SellersOrganizationServiceInstance.LoadEntities(s => s.ID == o.SellersOrganization.ParentOrganizationId).Select(n =>
                    n.OrganizationName),
                o.SellersOrganizationId,
                o.IsAvailable,
                CreateTime = o.CreateTime.ToString("yyyy-MM-dd hh:mm:ss"),
                OrganizationNameDesc = o.SellersOrganization.OrganizationName,
                EmployeeCount = o.SellerEmployee.Any() ? o.SellerEmployee.Count() : 0
            });
            return Json(new
             {
                 sEcho = model.sEcho,
                 iTotalRecords = total,
                 iTotalDisplayRecords = total,
                 aaData = list
             }, JsonRequestBehavior.AllowGet);
        }
        #region 判断销售商名称是否相同
        public bool IsExistSellers(string sellerName)
        {
            return ServiceFactory.SellersServiceInstance.IsExist(sellerName,0, 0);
        }
       #endregion
        #region 添加销售商详情
        /// <summary>
        ///添加或修改
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Edit()
        {
            var sellerList = new List<Sellers> { new Sellers() };
            return View(sellerList);
        }
        #endregion

        #region 修改经销商IsAvailable状态
        [HttpPost]
        public JsonResult UpdateSellerStatus(int id, bool isAvailable)
        {
            var entity = ServiceFactory.SellersServiceInstance.LoadByID(id);
            var success = false;
            if (entity != null)
            {
                entity.IsAvailable = isAvailable;
                entity.LastModifyTime = DateTime.Now;
                entity.LastModifyBy = CurrentUser.UserAccount;
                success = ServiceFactory.SellersServiceInstance.UpdateEntities(entity);
            }
            return Json(new
            {
                success = success,
                message = success ? "修改成功" : "修改失败"
            });
        }
        #endregion

        #region 修改经销商信息
        [HttpPost]
        public JsonResult UpdateSellers(Sellers model)
        {
            var success = false;
            if (model != null)
            {
                var entity = ServiceFactory.SellersServiceInstance.LoadByID(model.ID);
                if (entity != null)
                {
                    entity.LastModifyTime = DateTime.Now;
                    entity.LastModifyBy = CurrentUser.UserAccount;
                    entity.SellersName = model.SellersName;
                    entity.SellersType = model.SellersType;
                    entity.SellerCode = model.SellerCode;
                    entity.SellersOrganizationId = model.SellersOrganizationId==0 ? entity.SellersOrganizationId : model.SellersOrganizationId;
                    entity.SaleSystemType = model.SaleSystemType;
                    success = ServiceFactory.SellersServiceInstance.UpdateEntities(entity);
                }
            }
            return Json(new
            {
                success = success,
                message = success ? "成功" : "失败"
            });
        }
        #endregion

        #region 添加销售商
        /// <summary>
        /// 
        /// </summary>
        /// <param name="Sellers">必须与前台Model保持一致（id前缀）</param>
        /// <returns></returns>
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult SaveSellers(List<Sellers> Sellers)
        {
            var responseResult = new ResponseResult
            {
                OpreateType = OpreateType.Add
            };
            var serv = ServiceFactory.SellersServiceInstance;
            foreach (var item in Sellers)
            {
                if (serv.IsExist(item.SellersName, item.SellersType, item.SellersOrganizationId) ||serv.IsExist(item.SellerCode))
                {
                    responseResult.Message = "已存在相同信息的销售商或者有相同销售商代码";
                }
                else
                {
                    item.CreateTime = DateTime.Now;
                    item.CreateBy = CurrentUser.UserAccount;
                    item.LastModifyBy = CurrentUser.UserAccount;
                    item.LastModifyTime = DateTime.Now;
                    item.IsAvailable = true;
                    var entyli = serv.AddEntities(item);
                    responseResult.Success = entyli.ID > 0;
                }
            }
            TempData["ResponseResult"] = responseResult;
            return RedirectToAction("Index");
        }
        #endregion

        #region 导出保险产品详情
        /// <summary>  
        /// 
        /// </summary>  
        /// <returns></returns>  
        public ActionResult ExportSellersDetails(string content, SellersOrganizationModel model1)
        {
            SellersModel model = JsonConvert.DeserializeObject<SellersModel>(content);
            var total = 0;
            model.iDisplayStart = 0;
            model.iDisplayLength = int.MaxValue;
            model.iSorts = "ID desc";
            model1.iDisplayStart = 0;
            model1.iDisplayLength = int.MaxValue;
            model1.iSorts = "ID desc";
            var list = ServiceFactory.SellersServiceInstance.GetPagingList(model, out total).AsNoTracking().ToList().Select(o => new
            {
                ID = o.ID < 10 ? "V000" + o.ID : o.ID < 100 ? "V00" + o.ID : o.ID < 1000 ? "V0" + o.ID : o.ID < 10000 ? "V" + o.ID : "",
                o.SellersName,
                o.SellersType1.SellerTypeName,
                ParentOrganizationName = (ServiceFactory.SellersOrganizationServiceInstance.GetPagingList(model1, out total).AsNoTracking().ToList().Where(s => s.ID == o.SellersOrganization.ParentOrganizationId).Select(n => new
                {
                    OrganizationName = n.OrganizationName != null ? n.OrganizationName : string.Empty
                })).Last().OrganizationName,
                OrganizationNameDesc = o.SellersOrganization.OrganizationName,
                EmployeeCount = o.SellerEmployee.Count() > 0 ? o.SellerEmployee.Count() : 0
            });
            var dt = ListToDatatableHelper.ToDataTable(list.ToList());
            dt.TableName = "List";
            //DataTable dt = ServiceFactory.InsuranceProductsServiceInstance.SqlQuery(sql, parameters);//获取需要导出的datatable数据  
            List<DataTable> dataSoure = new List<DataTable>();
            dataSoure.Add(dt);
            Dictionary<string, object> dic = new Dictionary<string, object>();
            //模板路径
            string execlPath = Server.MapPath("\\").Trim('\\') + "\\DownLoad\\Template\\SellersList.xlsx";
            string fileName = "SellersList-(" + DateTime.Now.ToString("yyyyMMdd") + ")";
            ExcelHelper.ExportToExcel(execlPath, dic, dataSoure, fileName);
            return Json(new object { });
        }
        #endregion

        #region 查看销售商详情
        public ActionResult Detail(int id)
        {
            var order = ServiceFactory.SellersServiceInstance.LoadByID(id);
            return View(order);
        }
        #endregion
        
        [HttpPost]
        public JsonResult UpdateSellerEmployee(int id, bool isAvailable, int sellerID)
        {
            List<SellerEmployee> list = new List<SellerEmployee>();
            if (id == 0)
            {
                list = ServiceFactory.SellerEmployeeServiceInstance.LoadBySellerID(sellerID);
            }
            else
            {
                SellerEmployee entity = ServiceFactory.SellerEmployeeServiceInstance.LoadByID(id);
                if (entity != null)
                {
                    list.Add(entity);
                }
            }
            var success = false;
            if (list.Count > 0)
            {
                foreach (var item in list)
                {
                    item.IsAvailable = isAvailable;
                    success = ServiceFactory.SellerEmployeeServiceInstance.UpdateEntities(item);
                }
            }
            return Json(new
            {
                success = success,
                message = success ? "修改成功" : "修改失败"
            });
        }
        [HttpPost]
        public JsonResult UpdateSellerInsuranceProducts(int id, bool isAvailable)
        {
            List<SellerInsuranceProducts> list = new List<SellerInsuranceProducts>();
            var success = false;
            if (id == 0)
            {
            }
            else
            {
                SellerInsuranceProducts entity = ServiceFactory.SellerInsuranceProductsServiceInstance.LoadById(id);
                if (entity != null)
                {
                    list.Add(entity);
                }
            }

            if (list.Count > 0)
            {
                foreach (var item in list)
                {
                    item.IsAvailable = isAvailable;
                    success = ServiceFactory.SellerInsuranceProductsServiceInstance.UpdateEntities(item);
                }
            }
            return Json(new
            {
                success = success,
                message = success ? "修改成功" : "修改失败"
            });
        }

        #region 导出人员详情
        /// <summary>  
        /// 
        /// </summary>  
        /// <returns></returns>  
        public ActionResult ExportSellerEmployee(SellerEmployeeModel model)
        {
            var total = 0;
            model.iDisplayStart = 0;
            model.iDisplayLength = int.MaxValue;
            model.iSorts = "ID desc";
            var list = ServiceFactory.SellerEmployeeServiceInstance.GetPagingList(model, out total).AsNoTracking().ToList().Select(o => new
            {
                o.UserName,
                o.CertificateNO,
                o.UserPhone,
                o.Email,
                IsAvailableStatus = o.IsAvailable ? "	生效中" : "已暂停"
            });
            var dt = ListToDatatableHelper.ToDataTable(list.ToList());
            dt.TableName = "List";
            //DataTable dt = ServiceFactory.InsuranceProductsServiceInstance.SqlQuery(sql, parameters);//获取需要导出的datatable数据  
            List<DataTable> dataSoure = new List<DataTable>();
            dataSoure.Add(dt);
            Dictionary<string, object> dic = new Dictionary<string, object>();
            //模板路径
            string execlPath = Server.MapPath("\\").Trim('\\') + "\\DownLoad\\Template\\SellerEmployeeList.xlsx";
            string fileName = "SellerEmployeeList-(" + DateTime.Now.ToString("yyyyMMdd") + ")";
            ExcelHelper.ExportToExcel(execlPath, dic, dataSoure, fileName);
            return Json(new object { });
        }
        #endregion

        [HttpPost]
        public JsonResult SelectSellersOrganization(int pareSellersOrganizationid)
        {
            var list =
                ServiceFactory.SellersOrganizationServiceInstance.GetSellersOrganizationAllByParentId(
                    pareSellersOrganizationid);
            var entity = list.ToList().Select(o => new
            {
                o.ID,
                o.OrganizationName
            }).ToList();
            bool status = true;
            return Json(new
            {
                success = status,
                aaData = entity
            }, JsonRequestBehavior.AllowGet);
        }
    }
}